package com.athuiju.fenxiaoback.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.athuiju.fenxiaoback.service.MsmService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {


    @Override
    public boolean send(Map<String, Object> param, String phone) {
        if(StringUtils.isEmpty(phone)) return false;

        /*
        default:地域节点，可以修改，比如上海，杭州等等。这里我们使用默认的
        第二个和第三个参数：就是之前我们用的accessKeyId和keysecret
         */
        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI1Xj2QzhTxKpw", "0xzt3fWH2mQslm0qumyphFj9VJGhk2");
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关固定的参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);//默认Post的不要改
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers",phone); //手机号
        request.putQueryParameter("SignName","杭州会聚人力"); //申请阿里云 签名名称
        request.putQueryParameter("TemplateCode","SMS_171075508"); //申请阿里云 模板code
        //验证码数据，我们的param是map格式数据，但是阿里云要的是json数据，所以把map转换成json数据传递
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();//通过返回值判断短信是否发送成功
            return success;
        }catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
